package com.woniuxy.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.order.entity.OrderInfo;
import com.woniuxy.order.entity.RecycleReceive;
import com.woniuxy.order.entity.Statistics;
import com.woniuxy.order.mapper.OrderInfoMapper;
import com.woniuxy.order.mapper.RecycleReceiveMapper;
import com.woniuxy.order.mapper.StatisticsMapper;
import com.woniuxy.order.service.IRecycleReceiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.permission.entity.Permission;
import com.woniuxy.permission.mapper.PermissionMapper;
import org.springframework.stereotype.Service;
import zsd.waste.form.InsertReForm;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 收货记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-13
 */
@Service
public class RecycleReceiveServiceImpl extends ServiceImpl<RecycleReceiveMapper, RecycleReceive> implements IRecycleReceiveService {

    @Resource
    private RecycleReceiveMapper recycleReceiveMapper;
    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private StatisticsMapper statisticsMapper;

    @Override
    public List<RecycleReceive> findOrderIdRr(Integer orderId, Integer pageNum, Integer pageSize) throws Exception {
        if (orderId==null){
            System.out.println("订单ID不能为空");
        }
        QueryWrapper<RecycleReceive> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_num",orderId).orderByDesc("creat_time");
        List<RecycleReceive> receiveList = recycleReceiveMapper.selectList(queryWrapper);
        return receiveList;
    }

    @Override
    public void ReallyWaste(Integer id, String verifyRemark, Integer verifyStatus) throws Exception {
        RecycleReceive recycleReceive = recycleReceiveMapper.selectById(id);
        OrderInfo orderInfo = orderInfoMapper.selectById(recycleReceive.getOrderNum());

        if (verifyStatus == 1) {
            orderInfo.setOrderState(5);
            recycleReceive.setVerifyRemark(verifyRemark);
            recycleReceive.setReceiverId(verifyStatus);

            // 查询是否已有该废品类型的统计记录
            QueryWrapper<Statistics> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("waste_type_id", recycleReceive.getWasteTypeId())
                    .apply("DATE_FORMAT(creat_time,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')");
            Statistics existingStat = statisticsMapper.selectOne(queryWrapper);

            if (existingStat != null) {
                // 已有记录则更新
                existingStat.setQuantity(existingStat.getQuantity() + recycleReceive.getQuantity());
                existingStat.setPrice(existingStat.getPrice() + recycleReceive.getConfirmedPrice());
                statisticsMapper.updateById(existingStat);
            } else {
                // 无记录则新增
                Statistics newStat = new Statistics()
                        .setWasteTypeId(recycleReceive.getWasteTypeId())
                        .setQuantity(recycleReceive.getQuantity())
                        .setPrice(recycleReceive.getConfirmedPrice())
                        .setCreatTime(LocalDateTime.now())
                        .setQuantityUnit(recycleReceive.getQuantityUnit());
                statisticsMapper.insert(newStat);
            }
        } else {
            orderInfo.setOrderState(7);
            recycleReceive.setVerifyRemark(verifyRemark);
            recycleReceive.setReceiverId(verifyStatus);
        }

        orderInfoMapper.updateById(orderInfo);
        recycleReceiveMapper.updateById(recycleReceive);
    }

    @Override
    public void InsertRr(List<InsertReForm> forms, Integer orderNum, Integer userId) throws Exception {
        Permission permission = permissionMapper.selectById(userId);
        OrderInfo orderInfo = orderInfoMapper.selectById(orderNum);

        List<RecycleReceive> receiveList = forms.stream().map(form -> {
            RecycleReceive recycleReceive = new RecycleReceive();
            recycleReceive.setReceiverId(userId);
            recycleReceive.setReceiverName(permission.getName());
            recycleReceive.setReceiveTime(LocalDateTime.now());
            recycleReceive.setWasteTypeId(form.getWasteTypeId());
            recycleReceive.setQuantity(form.getQuantity());
            recycleReceive.setQuantityUnit(form.getQuantityUnit());
            recycleReceive.setOrderNum(orderNum);
            recycleReceive.setConfirmedPrice(form.getConfirmedPrice());
            return recycleReceive;
        }).collect(Collectors.toList());

        orderInfo.setOrderState(5);
        orderInfoMapper.updateById(orderInfo);
        receiveList.forEach(recycleReceiveMapper::insert);
    }
}
